package com.boot.unity.api.filter;

import com.alibaba.fastjson.JSON;
import com.boot.unity.api.common.ResponseResult;
import com.boot.unity.api.common.Result;
import com.boot.unity.api.common.ResultCodeEnum;
import com.boot.unity.api.constants.Constants;
import com.boot.unity.api.utils.IpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;

@Slf4j
@Order(0)
@Component
@ConditionalOnProperty(name = "spring.profiles.active",havingValue = "prod")
public class ParamsValidateFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        AntPathMatcher matcher = new AntPathMatcher();
        String uri = request.getRequestURI();
        if (matcher.match(Constants.API_URI_PREFIX,uri)){
            Set<String> keys = request.getParameterMap().keySet();
            /** 放行排除的地址 */
            if (Constants.EXCLUDE_PATH.contains(uri)){
                filterChain.doFilter(request,response);
            }else if (keys.containsAll(Constants.PARAM_KEYS)){
                filterChain.doFilter(request,response);
            }else {
                log.error("缺少必要的参数，请求接口：{}，请求IP：{}，请求参数：{}",
                        uri,
                        IpUtil.getIpAddress(request),
                        JSON.toJSONString(request.getParameterMap()));
                Result result = new Result(ResultCodeEnum.DATA_FORMAT_ERROR);
                ResponseResult.toJsonResult(response,result);
            }
        }else {
            filterChain.doFilter(request,response);
        }
    }
}
